package com.think.admin.oauth.util;

import com.think.admin.oauth.rbac.RbacGrantedAuthority;
import com.think.admin.oauth.rbac.RbacUserDetails;
import com.think.common.exception.SysException;
import com.think.common.utils.SysUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.HashSet;
import java.util.Set;

/**
 * <p>
 * oauth2 工具类
 * </p>
 *
 * @author: xwj
 * @data: 2019-05-17
 */
public class OAuthUtil {

    /**
     * 获取用户信息
     *
     * @return java.lang.Long
     * @author xwj
     * @data 2019/5/16
     */
    public static RbacUserDetails getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (SysUtils.isEmpty(authentication)) {
            throw new SysException("系统错误，登录信息异常");
        }
        Object principal = authentication.getPrincipal();
        if (SysUtils.isEmpty(principal) || !(principal instanceof RbacUserDetails)) {
            throw new SysException("系统错误，登录信息异常");
        }
        return (RbacUserDetails) principal;
    }

    /**
     * 获取用户ID
     *
     * @return java.lang.Long
     * @author xwj
     * @data 2019/5/16
     */
    public static String getUserId() {
        return getUser().getUserId();
    }

    /**
     * 获取用户权限
     *
     * @return java.lang.Long
     * @author xwj
     * @data 2019/5/16
     */
    public static Set<RbacGrantedAuthority> getUserPermissions() {
        Set<RbacGrantedAuthority> userPermissions = getUser().getAuthorities();
        if (null == userPermissions) {
            return new HashSet<>(0);
        } else {
            return userPermissions;
        }
    }
}
